package one.stand.event;

import cn.hutool.core.util.StrUtil;
import com.jmp.base.dto.MessagePushRequest;
import com.jmp.base.dto.MessagePushType;
import com.jmp.feign.MessageFeign;
import lombok.extern.slf4j.Slf4j;
import one.stand.dto.Company2Dto;
import one.stand.enums.OrderStateEnum;
import one.stand.mapper.*;
import one.stand.model.*;
import one.stand.service.CompanyBaseService;
import one.stand.util.DateUtil;
import one.stand.util.MoneyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import java.util.List;
import java.util.stream.Collectors;

@Component
@Async("asyncServiceExecutor")
@Slf4j
public class OrderEventListener {
    @Autowired
    private MessageFeign messageFeign;

    @Autowired
    private CompanyBaseService companyBaseService;
    @Autowired
    private OrderinfoPublicMapper orderinfoPublicMapper;
    @Autowired
    private RoyaltyRecordMapper royaltyRecordMapper;
    @Autowired
    private CompanyTransferMapper companyTransferMapper;

    @Autowired
    private OrdersMapperExt ordersMapperExt;
    @Autowired
    private OrderInfoMapperExt orderInfoMapperExt;

    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    public void orderComplete(OrderCompleteEvent event) {
        log.info("event handler:{}", event.getSource());

        // 商品订单完成后提成佣金和转账到公司拥有人
//        companyRoyalty(event.getOrderId());

        // 推送交易消息
        Orders orders = ordersMapperExt.selectByPrimaryKey(event.getOrderId());
        Company2Dto company2Dto = companyBaseService.get2(orders.getCompanyId());
        List<OrderInfo> list = orderInfoMapperExt.selectByOrderId(orders.getOrdersId());
        String goodsNames = list.stream().map(OrderInfo::getGoodsName).collect(Collectors.joining(StrUtil.COMMA));

        String[] fillData = {orders.getOrdersNo(), StrUtil.maxLength(goodsNames, 20),
                MoneyUtil.getWithUnit(orders.getOrderPrice()),
                OrderStateEnum.COMPLETE.getMessage()};
        MessagePushRequest pushRequest = MessagePushRequest.builder()
                .type(MessagePushType.ORDER_STATE_CRM)
                .toId(company2Dto.getUserId())
                .fillData(fillData)
                .build();
        messageFeign.push(pushRequest);
    }

    /**
     * 分销
     */
    private void companyRoyalty(Integer ordersId) {
        try {
            // 根据订单查询订单商品详情
            List<OrderinfoModel> list = orderinfoPublicMapper.selectComanyRoyalty(ordersId);
            if (list == null || list.size() <= 0) {
                return;
            }
            // 总提成金额
            Integer amount = 0;
            // 分销提成
            for (OrderinfoModel model : list) {
                boolean fal = model.getForwardId() != null && model.getAllPrice() > 0 && model.getRoyaltyRatio() > 0;
                if (fal) {
                    RoyaltyRecordModel royaltyRecordModel = new RoyaltyRecordModel();
                    // 提现订单号
                    String recordNo = getRecordNo();
                    Integer money = model.getAllPrice() * model.getRoyaltyRatio() / 100;
                    // 微信提现操作
                    ResultModel resultModel = ResultModel.fail("暂不能提现~！");/*wxPayService.doCash(recordNo, model.getOpenId(), money, ip, companyKey);*/
                    royaltyRecordModel.setRecordNo(recordNo);
                    royaltyRecordModel.setOrderMoney(model.getAllPrice());
                    royaltyRecordModel.setRoyaltyMoney(money);
                    royaltyRecordModel.setUserId(model.getUserId());
                    royaltyRecordModel.setCreateTime(DateUtil.currentDate());
                    royaltyRecordModel.setIsDel(0);
                    royaltyRecordModel.setLevel(model.getLevel());
                    royaltyRecordModel.setType(1);
                    royaltyRecordModel.setCompanyId(model.getCompanyId());
                    royaltyRecordModel.setOrdersId(model.getOrderInfoId());
                    if (resultModel.isSuccess()) {
                        royaltyRecordModel.setState(1);
                    } else {
                        royaltyRecordModel.setState(0);
                        royaltyRecordModel.setRemark(resultModel.getMessage());
                    }
                    // 保存分销金额记录
                    royaltyRecordMapper.insertSelective(royaltyRecordModel);
                    // 累计提成金额
                    amount += money;
                }
            }
            // 商城公司拥有人提现
            OrderinfoModel orderinfoModel = list.get(0);
            CompanyTransferModel companyTransferModel = new CompanyTransferModel();
            // 提现订单号
            String transferNo = getRecordNo();
            Integer money = orderinfoModel.getPayPrice() - amount;
            // 微信提现操作
            ResultModel resultModel = ResultModel.fail("暂不能提现~！");/*wxPayService.doCash(transferNo, orderinfoModel.getCompanyOpenId(), money, ip, companyKey);*/
            companyTransferModel.setTransferNo(transferNo);
            companyTransferModel.setOrderAmount(orderinfoModel.getPayPrice());
            companyTransferModel.setRoyaltyAmount(amount);
            companyTransferModel.setTransferAmount(money);
            companyTransferModel.setUserId(orderinfoModel.getCompanyUserId());
            companyTransferModel.setCreateTime(DateUtil.currentDate());
            companyTransferModel.setIsDel(0);
            companyTransferModel.setCompanyId(orderinfoModel.getCompanyId());
            companyTransferModel.setOrdersId(ordersId);
            if (resultModel.isSuccess()) {
                companyTransferModel.setState(1);
            } else {
                companyTransferModel.setState(0);
                companyTransferModel.setRemark(resultModel.getMessage());
            }
            // 保存分销金额记录
            companyTransferMapper.insertSelective(companyTransferModel);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    private String getRecordNo() {
        return "TX" + System.currentTimeMillis() + "" + (int) (1 + Math.random() * (9999));
    }
}
